package com.dave.admin.modular.boss.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dave.admin.common.result.CommonResult;
import com.dave.admin.component.log.SysLog;
import com.dave.admin.modular.boss.dto.PermissionNode;
import com.dave.admin.modular.boss.dto.UserAdminRolePermParam;
import com.dave.admin.modular.boss.entity.RolePermission;
import com.dave.admin.modular.boss.service.IRolePermissionService;
import com.dave.admin.modular.boss.service.IUserRoleService;
import com.dave.admin.modular.boss.service.IPermissionService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 权限配置菜单
 *
 * @author Dave
 */
@RestController
@RequestMapping("/boss/permission")
@AllArgsConstructor
public class PermissionController {

    private final IPermissionService iPermissionService;

    private final IRolePermissionService iRolePermissionService;

    private final IUserRoleService iUserRoleService;


    /**
     * 权限树数据
     *
     * @param roleId 角色id
     * @return
     */
    @GetMapping(value = "/treeList/{roleId}")
    public CommonResult treeList(@PathVariable String roleId) {

        List<PermissionNode> permissionNodeList = iPermissionService.treeList();
        List<String> permissionIds = iRolePermissionService.listObjs(new QueryWrapper<RolePermission>().select(RolePermission.PERMISSION_ID)
                .eq(RolePermission.ROLE_ID, roleId), o -> o.toString());

        Map result = MapUtil.builder()
                .put("permNode", permissionNodeList)
                .put("value", permissionIds)
                .build();
        return CommonResult.success(result);
    }


    /**
     * 角色归属下的用户数据
     *
     * @param roleId 角色id
     * @return
     */
    @GetMapping(value = "/treeUser/{roleId}")
    public CommonResult treeUser(@PathVariable String roleId) {
        return CommonResult.success(iUserRoleService.treeUser(roleId));
    }


    /**
     * 保存角色关联的用户
     */
    @SysLog("保存角色关联的用户")
    @PostMapping(value = "/saveRoleConfig")
    public CommonResult holeUser(@RequestBody UserAdminRolePermParam userAdminRolePermParam) {
        iUserRoleService.relationshipUser(userAdminRolePermParam);
        return CommonResult.success();
    }
}
